import {HttpClient, HttpEventType, HttpHeaders, HttpRequest} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {ConfigProvider} from "../config/config";
import {UtilsProvider} from "../utils/utils";

@Injectable()
export class HttpServicesProvider {
    //application/x-www-form-urlencoded
    private headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'});

    constructor(
        public config: ConfigProvider,
        public http: HttpClient,
        public util: UtilsProvider
    ) {

    }

    requestData(apiUrl, callback) {
        this.http.jsonp(this.config.apiUrl + apiUrl, 'callback').subscribe(function (data) {
            callback(data);
        });
    }

    requestPostData(apiUrl, data, callback) {
        this.http.post(this.config.apiUrl + apiUrl, this.util.serializeParams(data), {
            headers: this.headers
        }).subscribe(function (response) {
            callback(response);
        });
    }

    uploadImage(apiUrl, data, callback) {
        let loadObj = this.util.loading({
            content: '正在上传，请稍后...'
        });
        loadObj.show();
        const request = new HttpRequest("POST", this.config.apiUrl + apiUrl, data, {reportProgress: true});
        this.http.request(request).subscribe(
            event => {
                if (event.type === HttpEventType.Response) {
                    loadObj.close();
                    callback(event.body);
                }
            }
        );
    }

}
